package com.faxsun.web.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.GenericFilterBean;

import com.faxsun.captcha.constants.CaptchaType;
import com.faxsun.captcha.service.FSCaptchaService;
import com.faxsun.captcha.service.FSDigitalCaptchaServiceImpl;
import com.faxsun.core.web.security.FraudConstants;

/**
 * 验证码验证过滤器
 *
 * @author zhaoteng.song@faxsun.com
 */
public class CaptchaVerificationFilter extends GenericFilterBean {

    // FIXME:验证码过滤器在applicationContext-security.xml中配置，配置在PRE_AUTH_FILTER之前

    protected static final Log LOG = LogFactory.getLog(CaptchaVerificationFilter.class);

    /**
     * 验证验证码是否正确
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();
        // session中读取验证标记
        Boolean isRequired = (Boolean) session.getAttribute(FraudConstants.IS_CAPTCHA_REQUIRED);

        String url = httpRequest.getRequestURI();

        if (isRequired != null && isRequired && url.endsWith("/login_post.htm")) {
            String captchaResp = httpRequest.getParameter("captcha");
            Boolean result = Boolean.FALSE;
            if (captchaResp != null && !captchaResp.isEmpty()) {
                FSCaptchaService captchaService = FSDigitalCaptchaServiceImpl.getSingleInstance();
                // session中获取验证码类型
                CaptchaType type = (CaptchaType) session.getAttribute(FraudConstants.CAPTCH_TYPE);
                result = captchaService.validateResponseForID(session.getId(), captchaResp, type);
            }

            if (result == null) {
                LOG.error("Unknown captcha type result=null");
            } else {
                if (!result) {
                    HttpServletResponse resp = (HttpServletResponse) response;
                    String msg = "验证码错误，请重新输入登录信息";
                    resp.sendRedirect(httpRequest.getContextPath() + "/login?error=true&msg="
                        + URLEncoder.encode(msg, "UTF-8"));
                    return;
                } else {
                    // 验证成功，移除验证码标志位
                    session.removeAttribute(FraudConstants.IS_CAPTCHA_REQUIRED);
                }
            }
        }

        chain.doFilter(request, response);
    }
}